<template>
  <div>
    <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="书名:">
            <el-input v-model="form.bookName"></el-input>
        </el-form-item>
        <el-form-item label="封面:">
            

            <el-upload
            :action="imageuploadURL"
            list-type="picture-card"
            ref="pictureUpload"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            :on-exceed="handleExceed"
            :limit="1">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url" alt=""
                >
                <span class="el-upload-list__item-actions">
                    <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                    >
                    <i class="el-icon-zoom-in"></i>
                    </span>
                    <span class="el-upload-list__item-delete" @click="removePicture(file)">
                  <i class="el-icon-delete"></i>
                </span>
                </span>       
                </div>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>


        </el-form-item>
        <el-form-item label="作者:">
            <el-input v-model="form.author"></el-input>
        </el-form-item>
        <el-form-item label="出版社:">
            <el-input v-model="form.publisher"></el-input>
        </el-form-item>
        <el-form-item label="出版日期:">
            <el-date-picker
                v-model="form.publishDate"
                type="date"
                placeholder="出版日期">
                </el-date-picker>
        </el-form-item>
        <el-form-item label="图书编号:">
            <el-input v-model="form.bookNo"></el-input>
        </el-form-item>
        <el-form-item label="图书类型:">
            <el-select v-model="form.bookType"
                       placeholder="请选择图书类型">
              <el-option v-for="(item, index) in TypeList"
                         :key="index"
                         :label="item.name"
                         :value="item.id" />
            </el-select>
        </el-form-item>
        <el-form-item label="数量:">
            <el-input-number v-model="form.amount"></el-input-number>
        </el-form-item>
        <el-form-item label="简介:">
            <el-input type="textarea"
            :rows="2" 
            v-model="form.description"
            placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="addbook">添加</el-button>
            <el-button @click="reset">重置</el-button>
        </el-form-item>
        </el-form>
  </div>
</template>

<script>
import axios from "axios"
export default {
    data () {
        return {
        imageuploadURL: this.url + "/upload/image",
        form: {
          bookName: '',
          image: '',
          publishDate: '',
          publisher: '',
          bookType: '',
          author:'',
          bookNo:'',
          amount:'',
          description:'',
        },
        TypeList:[],

        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false
        }
    },
    methods: {
         msToDate(msec){
            let datetime = new Date(msec);
            let year = datetime.getFullYear();
            let month = datetime.getMonth();
            let date = datetime.getDate();
           /*  let hour = datetime.getHours();
            let minute = datetime.getMinutes();
            let second = datetime.getSeconds(); */
        
            /* let result1 = year + 
                        '-' + 
                        ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) + 
                        '-' + 
                        ((date + 1) < 10 ? '0' + date : date) + 
                        ' ' + 
                        ((hour + 1) < 10 ? '0' + hour : hour) +
                        ':' + 
                        ((minute + 1) < 10 ? '0' + minute : minute) + 
                        ':' + 
                        ((second + 1) < 10 ? '0' + second : second); */
        
            let result2 = year + 
                 '-' + 
                 ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) + 
                 '-' + 
                 ((date + 1) < 10 ? '0' + date : date);
        
            return result2;
        },

        /* 上传头像之前检查文件类型 */
        beforeImageUpload(file){
            const isIMG =
            file.type === 'image/jpg' ||
            file.type === 'image/jpeg' ||
            file.type === 'image/png'
            if (!isIMG) {
            this.$message.error('上传头像图片只支持jpg、jpeg、png格式!')
            }
            
            return isIMG
        },

        // 超出限制提示
        handleExceed () {
        this.$message.warning(`当前限制选择 1个文件`)
        },

        handleImageSuccess(res){
            this.form.image = res.data
            this.$message.success("图片上传成功")
        },

         //上传成功执行清空
        removePicture (file) {
            this.$refs.pictureUpload.handleRemove(file)
            if(this.form.image != '' && this.form.image != null){
                axios.get(this.url + "/upload/dimage",{
                    params:{
                        fileName:this.form.image
                    }     
                }).then(() => {
                    
                }).catch(() => {
                    this.$message.error("出现错误,请联系管理员")
                })
            }
            this.form.image = ''
        },

        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },

        
        addbook() {
            /* 判断日期是否正确 */
            if(this.form.publishDate > new Date()){
                this.$message.warning("请输入正确的出版日期")
                return
            }
            /* 将中国标准时间转换 */
            this.form.publishDate = this.msToDate(this.form.publishDate)
            this.form.bookName=this.form.bookName.trim()
            this.form.publisher=this.form.publisher.trim()
            this.form.description=this.form.description.trim()
            if(this.form.bookName == "" || this.form.publishDate=='' || this.form.publisher=='' || this.form.author=='' || this.form.amount==''||this.form.bookNo==''||this.form.description==''){
                this.$message.warning("字段不能为空")
                return
            }
            if(this.form.image==''){
                this.$message.warning("请上传图片")
                return
            }
            /* 检查格式 */
            var reg1 = /^[1-9]\d*$/;
            var reg2 = /^\w+$/;
            /* var reg3 = /^\d{1,20}$/ */
            if(!reg1.test(this.form.amount) || !reg2.test(this.form.bookNo)){
                this.$message.warning("请输入正确格式")
                return
            }
            /* if(!reg3.test(this.form.description)){
                this.$message.warning("简介限制240字")
                return
            } */
            axios.get(this.url + "/book/add",{
                params:{
                    bookName:this.form.bookName,
                    image:this.form.image,
                    publishDate:this.form.publishDate,
                    publisher:this.form.publisher,
                    author:this.form.author,
                    amount:this.form.amount,
                    bookNo:this.form.bookNo,
                    description:this.form.description,
                    bookType:this.form.bookType,
                    addUser:localStorage.getItem("username"),
                    updateUser:localStorage.getItem("username")
                }
            }).then((res) => {
                if(res.data.code == 1){
                    this.$message.success("添加成功")
                    this.form.bookName='',
                    this.form.publishDate='',
                    this.form.publisher='',
                    this.form.author='',
                    this.form.amount='',
                    this.form.bookNo='',
                    this.form.description='',
                    this.form.bookType=''
                    this.form.image=''
                    this.removePicture()
                    
                }else{
                    this.$message.error(res.data.msg)
                    
                }
            }).catch(() => {
                this.$message.error("操作失败")
            });
        },
      reset(){  
        this.removePicture()
        this.form.bookName='',
        this.form.publishDate='',
        this.form.publisher='',
        this.form.author='',
        this.form.amount='',
        this.form.bookNo='',
        this.form.description='',
        this.form.bookType=''
        this.form.image=''
      }
    },
    mounted () {
        //获取图书分类
        axios.get(this.url + "/book/type").then((res) => {
            if(res.data.code == 1){
                this.TypeList = res.data.data
            }else{
                this.$message.error("相关信息未加载成功，请刷新")
            }
        }).catch(() => {
            this.$message.error("信息加载失败")
        });
    }
}
</script>

<style>

</style>